package com.tangdada.whacmole.base;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.tangdada.whacmole.ImageUtil;


/**
 * 简易精灵类
 * Created by wjy on 2018/4/12
 */

public class Sprite {

    public float posX;
    public float posY;
    public float width;
    public float height;
    public Bitmap[] bitmaps;//可能会有动画，多组
    public String imagePath[];
    public int currentFrame;//当前帧
    public Paint paint;//画笔，此处用于点击事件处理
    public boolean canPress;
    public int anim_times = -1;//动画次数

    public Sprite(String... path) {
        if (path != null) {
            imagePath = new String[path.length];
            int index = 0;
            for (String s : path) {
                this.imagePath[index] = s;
                index++;
            }
            load();
        }
    }

    public void setCanPress(boolean press) {
        canPress = press;
    }

    protected void load() {
        paint = new Paint();
        if (imagePath == null || imagePath.length == 0) return;
        bitmaps = new Bitmap[imagePath.length];
        int index = 0;
        for (String p : imagePath) {
            try {
                bitmaps[index] = ImageUtil.loadBitmap(p);
                if (width == 0) {
                    width = bitmaps[index].getWidth();
                    height = bitmaps[index].getHeight();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
            index++;
        }
    }

    public void playAnimation(int times) {
        anim_times = times;
    }

    public void setPosition(float x, float y) {
        this.posX = x;
        this.posY = y;
    }

    public void onDraw(Canvas c) {
//        menu_paint.setAlpha(canPress ? 100 : 255);
        c.drawBitmap(bitmaps[currentFrame], posX, posY, paint);
        onUpdate();
    }

    public void onUpdate(){
        if (anim_times > 0 ) nextFrame();
    }

    //循环播放，这里偷懒，不加控制循环次数了
    public void nextFrame() {
        currentFrame++;
        if (currentFrame >= bitmaps.length) {
            currentFrame = 0;
            anim_times--;
        }
    }

    public int getAnimFrame(){
        return currentFrame;
    }

    public void setFrame(int frameIndex) {
        currentFrame = frameIndex;
        currentFrame = currentFrame >= bitmaps.length ? 0 : currentFrame;
    }

    //是否点中自己
    public boolean isTouchMe(float x, float y) {
        return x > posX && y > posY && x < (posX + width) && y < (posY + height);
    }

    public void recycle() {
        if (bitmaps != null) {
            for (Bitmap bitmap : bitmaps) {
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        }
    }

}
